package com.bl.nio.client.handler;

import com.bl.nio.common.entity.SocketClient;
import com.bl.nio.common.handler.IEventHandler;
import com.bl.nio.common.pack.EventPack;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

/**
 * @author 作者 : blownsow
 * @version 版本: 1.0
 * @date 创建时间 : 2019/12/7 11:24
 * @describe 类描述:
 */
public class ClientHandler implements Runnable{
    private SocketClient client;

    private IEventHandler eventHandler;

    public ClientHandler(SocketClient client, IEventHandler eventHandler) {
        this.client = client;
        this.eventHandler = eventHandler;
    }

    @Override
    public void run() {
        int times = 0;
        while (client.getSocket().isConnected() && !client.getSocket().isClosed()){
            try {
                InputStream in = client.getSocket().getInputStream();
                int available = in.available();
                if (available > 0){
                    times = 0;
                    ObjectInputStream objectInputStream = new ObjectInputStream(in);
                    Object object = objectInputStream.readObject();
                    if (object instanceof EventPack){
                        eventHandler.onEventPack(client,(EventPack)object);
                    }
                    eventHandler.onMessage(client,object);
                }
                Thread.sleep(100);

//                times += 100;
//                if (times >= client.getTimeout() && client.getTimeout() != 0){
//                    client.close();
//                    break;
//                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        eventHandler.onDisConnect(client);
    }
}
